<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>编辑产品</title>
    
    <!-- Vuetify 3 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/@mdi/font@7.0.96/css/materialdesignicons.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/vuetify@3.4.0/dist/vuetify.min.css" rel="stylesheet">
    
    <!-- Vue 3 -->
    <script src="https://unpkg.com/vue@3.3.4/dist/vue.global.js"></script>
    <!-- Vuetify 3 JS -->
    <script src="https://cdn.jsdelivr.net/npm/vuetify@3.4.0/dist/vuetify.min.js"></script>
</head>
<body>
    <div id="app">
        <v-app>
            <v-main>
                <v-container>
                    <v-card class="mx-auto" max-width="800">
                        <v-card-title class="text-h5">
                            编辑产品
                        </v-card-title>
                        
                        <v-card-text>
                            <v-form ref="form">
                                <v-row>
                                    <!-- 字符串输入框 - 产品名称 -->
                                    <v-col cols="12" md="6">
                                        <v-text-field
                                            v-model="formData.name"
                                            label="产品名称 *"
                                            :rules="nameRules"
                                            required
                                            variant="outlined"
                                            @input="onFieldChange('name', $event.target.value)"
                                        ></v-text-field>
                                    </v-col>
                                    
                                    <!-- 字符串输入框 - SKU编码 -->
                                    <v-col cols="12" md="6">
                                        <v-text-field
                                            v-model="formData.sku"
                                            label="SKU编码 *"
                                            :rules="skuRules"
                                            required
                                            variant="outlined"
                                            @input="onFieldChange('sku', $event.target.value)"
                                        ></v-text-field>
                                    </v-col>
                                    
                                    <!-- 浮点数输入框 - 价格 -->
                                    <v-col cols="12" md="6">
                                        <v-text-field
                                            v-model="formData.price"
                                            label="价格 *"
                                            :rules="priceRules"
                                            type="number"
                                            step="0.01"
                                            variant="outlined"
                                            @input="onFieldChange('price', parseFloat($event.target.value) || 0)"
                                        ></v-text-field>
                                    </v-col>
                                    
                                    <!-- 整数输入框 - 库存数量 -->
                                    <v-col cols="12" md="6">
                                        <v-text-field
                                            v-model="formData.stock_quantity"
                                            label="库存数量 *"
                                            :rules="quantityRules"
                                            type="number"
                                            variant="outlined"
                                            @input="onFieldChange('stock_quantity', parseInt($event.target.value) || 0)"
                                        ></v-text-field>
                                    </v-col>
                                    
                                    <!-- 浮点数输入框 - 重量 -->
                                    <v-col cols="12" md="6">
                                        <v-text-field
                                            v-model="formData.weight"
                                            label="重量(kg)"
                                            type="number"
                                            step="0.01"
                                            variant="outlined"
                                            @input="onFieldChange('weight', parseFloat($event.target.value) || 0)"
                                        ></v-text-field>
                                    </v-col>
                                    
                                    <!-- 下拉框 - 分类 -->
                                    <v-col cols="12" md="6">
                                        <v-select
                                            v-model="formData.category"
                                            :items="categoryOptions"
                                            label="分类 *"
                                            item-title="text"
                                            item-value="value"
                                            variant="outlined"
                                            @update:modelValue="onFieldChange('category', $event)"
                                        ></v-select>
                                    </v-col>
                                    
                                    <!-- 字符串文本域 - 描述 -->
                                    <v-col cols="12">
                                        <v-textarea
                                            v-model="formData.description"
                                            label="描述"
                                            variant="outlined"
                                            rows="3"
                                            @input="onFieldChange('description', $event.target.value)"
                                        ></v-textarea>
                                    </v-col>
                                    
                                    <!-- 复选框 - 是否激活 -->
                                    <v-col cols="12" md="6">
                                        <v-checkbox
                                            v-model="formData.is_active"
                                            label="是否激活"
                                            @change="onFieldChange('is_active', $event)"
                                        ></v-checkbox>
                                    </v-col>
                                    
                                    <!-- 复选框 - 是否推荐 -->
                                    <v-col cols="12" md="6">
                                        <v-checkbox
                                            v-model="formData.is_featured"
                                            label="是否推荐"
                                            @change="onFieldChange('is_featured', $event)"
                                        ></v-checkbox>
                                    </v-col>
                                    
                                    <!-- 日期选择器 - 创建日期 -->
                                    <v-col cols="12" md="6">
                                        <v-menu>
                                            <template v-slot:activator="{ props }">
                                                <v-text-field
                                                    v-model="formData.created_at"
                                                    label="创建日期"
                                                    prepend-icon="mdi-calendar"
                                                    readonly
                                                    v-bind="props"
                                                    variant="outlined"
                                                    @change="onFieldChange('created_at', $event.target.value)"
                                                ></v-text-field>
                                            </template>
                                            <v-date-picker
                                                v-model="formData.created_at"
                                                @update:modelValue="onDateChange('created_at', $event)"
                                            ></v-date-picker>
                                        </v-menu>
                                    </v-col>
                                    
                                    <!-- 日期选择器 - 更新日期 -->
                                    <v-col cols="12" md="6">
                                        <v-menu>
                                            <template v-slot:activator="{ props }">
                                                <v-text-field
                                                    v-model="formData.updated_at"
                                                    label="更新日期"
                                                    prepend-icon="mdi-calendar"
                                                    readonly
                                                    v-bind="props"
                                                    variant="outlined"
                                                    @change="onFieldChange('updated_at', $event.target.value)"
                                                ></v-text-field>
                                            </template>
                                            <v-date-picker
                                                v-model="formData.updated_at"
                                                @update:modelValue="onDateChange('updated_at', $event)"
                                            ></v-date-picker>
                                        </v-menu>
                                    </v-col>
                                </v-row>
                            </v-form>
                        </v-card-text>
                        
                        <v-card-actions>
                            <v-spacer></v-spacer>
                            <v-btn color="secondary" @click="cancelEdit">取消</v-btn>
                            <v-btn 
                                color="primary" 
                                @click="submitForm"
                                :loading="submitting"
                                :disabled="!formValid"
                            >
                                保存
                            </v-btn>
                        </v-card-actions>
                    </v-card>
                </v-container>
            </v-main>

            <!-- Snackbar 提示 -->
            <v-snackbar
                v-model="snackbar.show"
                :color="snackbar.color"
                :timeout="snackbar.timeout"
                top
            >
                {{ snackbar.text }}
                <template v-slot:actions>
                    <v-btn variant="text" @click="snackbar.show = false">关闭</v-btn>
                </template>
            </v-snackbar>
        </v-app>
    </div>

    <script>
        const { createApp } = Vue
        
        // 从 Django 模板中获取初始数据
        const initialData = {{ product_data|safe }};
        const categoryOptions = {{ category_options|safe }};
        
        const app = createApp({
            data() {
                return {
                    // 表单数据，从 Django 传递的 JSON 数据初始化
                    formData: {
                        id: initialData.id,
                        name: initialData.name,
                        sku: initialData.sku,
                        price: initialData.price,
                        stock_quantity: initialData.stock_quantity,
                        weight: initialData.weight,
                        category: initialData.category,
                        description: initialData.description,
                        is_active: initialData.is_active,
                        is_featured: initialData.is_featured,
                        created_at: initialData.created_at,
                        updated_at: initialData.updated_at,
                    },
                    
                    // 选项数据
                    categoryOptions: categoryOptions,
                    
                    // 监控变化的数据
                    changedFields: {},
                    
                    // 表单验证
                    formValid: true,
                    
                    // 提交状态
                    submitting: false,
                    
                    // 表单验证规则
                    nameRules: [
                        v => !!v || '产品名称不能为空',
                        v => (v && v.length <= 100) || '产品名称不能超过100个字符'
                    ],
                    skuRules: [
                        v => !!v || 'SKU编码不能为空',
                        v => /^[A-Z0-9]+$/.test(v) || 'SKU编码只能包含大写字母和数字'
                    ],
                    priceRules: [
                        v => !!v || '价格不能为空',
                        v => v >= 0 || '价格不能为负数'
                    ],
                    quantityRules: [
                        v => !!v || '库存数量不能为空',
                        v => v >= 0 || '库存数量不能为负数',
                        v => Number.isInteger(Number(v)) || '库存数量必须为整数'
                    ],
                    
                    // Snackbar 状态
                    snackbar: {
                        show: false,
                        text: '',
                        color: 'success',
                        timeout: 3000
                    }
                }
            },
            
            methods: {
                // 监控字段变化
                onFieldChange(fieldName, value) {
                    // 记录变化的字段
                    this.changedFields[fieldName] = value;
                    
                    // 更新表单数据
                    this.formData[fieldName] = value;
                    
                    console.log(`字段 ${fieldName} 发生变化:`, value);
                },
                
                // 日期变化处理
                onDateChange(fieldName, value) {
                    // 格式化日期为字符串
                    const formattedDate = value ? new Date(value).toISOString().split('T')[0] : '';
                    this.onFieldChange(fieldName, formattedDate);
                },
                
                // 提交表单
                async submitForm() {
                    if (this.$refs.form && !this.$refs.form.validate()) {
                        this.showSnackbar('请检查表单数据', 'error');
                        return;
                    }
                    
                    this.submitting = true;
                    
                    try {
                        const response = await fetch(`/api/products/${this.formData.id}/update/`, {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRFToken': this.getCsrfToken(),
                            },
                            body: JSON.stringify({
                                ...this.formData,
                                // 确保数值类型正确
                                price: parseFloat(this.formData.price) || 0,
                                stock_quantity: parseInt(this.formData.stock_quantity) || 0,
                                weight: parseFloat(this.formData.weight) || 0,
                            })
                        });
                        
                        const result = await response.json();
                        
                        if (result.success) {
                            this.showSnackbar('更新成功', 'success');
                            this.changedFields = {}; // 清空变化记录
                        } else {
                            this.showSnackbar(result.error || '更新失败', 'error');
                        }
                    } catch (error) {
                        console.error('提交错误:', error);
                        this.showSnackbar('网络错误，请重试', 'error');
                    } finally {
                        this.submitting = false;
                    }
                },
                
                // 取消编辑
                cancelEdit() {
                    // 检查是否有未保存的更改
                    if (Object.keys(this.changedFields).length > 0) {
                        if (confirm('您有未保存的更改，确定要离开吗？')) {
                            window.location.href = '/products/'; // 返回列表页
                        }
                    } else {
                        window.location.href = '/products/'; // 返回列表页
                    }
                },
                
                // 获取 CSRF Token
                getCsrfToken() {
                    // 从 Django 模板中获取 CSRF token
                    const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]');
                    return csrfToken ? csrfToken.value : '';
                },
                
                // 显示 Snackbar 提示
                showSnackbar(text, color = 'success') {
                    this.snackbar = {
                        show: true,
                        text: text,
                        color: color,
                        timeout: 3000
                    };
                }
            },
            
            mounted() {
                // 初始化 Vuetify
                const vuetify = Vuetify.createVuetify({
                    theme: {
                        defaultTheme: 'light'
                    }
                });
                
                this.$nextTick(() => {
                    app.use(vuetify);
                });
            }
        });
        
        app.mount('#app');
    </script>
</body>
</html>